#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
情绪分析HTTP服务
提供REST API接口进行情绪分析
"""

import json
import logging
from flask import Flask, request, jsonify
from flask_cors import CORS
from core.utils.emotionAnalyzer import emotion_analyzer

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
CORS(app)  # 允许跨域请求

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({
        "status": "healthy",
        "service": "emotion-analysis",
        "version": "1.0.0"
    })

@app.route('/emotion/analyze', methods=['POST'])
def analyze_text_emotion():
    """
    分析单条文本的情绪
    
    Request Body:
    {
        "text": "待分析的文本内容"
    }
    
    Response:
    {
        "emotion": "positive|negative|neutral",
        "confidence": 0.85,
        "method": "combined",
        "details": {...}
    }
    """
    try:
        data = request.get_json()
        if not data or 'text' not in data:
            return jsonify({
                "error": "Missing required field: text"
            }), 400
        
        text = data['text']
        if not text.strip():
            return jsonify({
                "emotion": "neutral",
                "confidence": 0.0,
                "method": "empty_text"
            })
        
        # 进行情绪分析
        result = emotion_analyzer.analyze_emotion_combined(text)
        
        logger.info(f"Analyzed text emotion: {result}")
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"Error analyzing text emotion: {e}")
        return jsonify({
            "error": str(e)
        }), 500

@app.route('/emotion/analyze/batch', methods=['POST'])
def analyze_batch_emotion():
    """
    批量分析多条文本的情绪
    
    Request Body:
    {
        "texts": ["文本1", "文本2", "文本3"]
    }
    
    Response:
    {
        "results": [
            {"emotion": "positive", "confidence": 0.85, ...},
            {"emotion": "negative", "confidence": 0.72, ...},
            ...
        ]
    }
    """
    try:
        data = request.get_json()
        if not data or 'texts' not in data:
            return jsonify({
                "error": "Missing required field: texts"
            }), 400
        
        texts = data['texts']
        if not isinstance(texts, list):
            return jsonify({
                "error": "texts must be a list"
            }), 400
        
        results = []
        for text in texts:
            if text and text.strip():
                result = emotion_analyzer.analyze_emotion_combined(text)
                results.append(result)
            else:
                results.append({
                    "emotion": "neutral",
                    "confidence": 0.0,
                    "method": "empty_text"
                })
        
        logger.info(f"Analyzed {len(texts)} texts")
        return jsonify({
            "results": results,
            "count": len(results)
        })
        
    except Exception as e:
        logger.error(f"Error analyzing batch emotion: {e}")
        return jsonify({
            "error": str(e)
        }), 500

@app.route('/emotion/chat-history', methods=['POST'])
def analyze_chat_history():
    """
    分析聊天记录的情绪趋势
    
    Request Body:
    {
        "chat_history": [
            {
                "chatType": 1,
                "content": "用户消息内容",
                "createdAt": "2025-01-23T14:30:15"
            },
            {
                "chatType": 2,
                "content": "智能体回复内容",
                "createdAt": "2025-01-23T14:30:16"
            }
        ]
    }
    
    Response:
    {
        "user_emotion": {...},
        "agent_emotion": {...},
        "emotion_trend": {...},
        "user_messages_count": 5,
        "agent_messages_count": 5
    }
    """
    try:
        data = request.get_json()
        if not data or 'chat_history' not in data:
            return jsonify({
                "error": "Missing required field: chat_history"
            }), 400
        
        chat_history = data['chat_history']
        if not isinstance(chat_history, list):
            return jsonify({
                "error": "chat_history must be a list"
            }), 400
        
        # 进行聊天记录情绪分析
        result = emotion_analyzer.analyze_chat_history(chat_history)
        
        logger.info(f"Analyzed chat history emotion: {len(chat_history)} messages")
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"Error analyzing chat history emotion: {e}")
        return jsonify({
            "error": str(e)
        }), 500

@app.route('/emotion/methods', methods=['GET'])
def get_available_methods():
    """
    获取可用的情绪分析方法
    
    Response:
    {
        "methods": [
            {
                "name": "snownlp",
                "description": "基于SnowNLP的情感分析",
                "supported": true
            },
            {
                "name": "keywords",
                "description": "基于关键词的情绪分析",
                "supported": true
            },
            {
                "name": "emoji",
                "description": "基于emoji的情绪分析",
                "supported": true
            },
            {
                "name": "combined",
                "description": "综合多种方法的情绪分析",
                "supported": true
            }
        ]
    }
    """
    try:
        methods = [
            {
                "name": "snownlp",
                "description": "基于SnowNLP的情感分析",
                "supported": True
            },
            {
                "name": "keywords", 
                "description": "基于关键词的情绪分析",
                "supported": True
            },
            {
                "name": "emoji",
                "description": "基于emoji的情绪分析", 
                "supported": True
            },
            {
                "name": "combined",
                "description": "综合多种方法的情绪分析",
                "supported": True
            }
        ]
        
        return jsonify({
            "methods": methods,
            "default_method": "combined"
        })
        
    except Exception as e:
        logger.error(f"Error getting available methods: {e}")
        return jsonify({
            "error": str(e)
        }), 500

@app.route('/emotion/test', methods=['GET'])
def test_emotion_analysis():
    """
    测试情绪分析功能
    
    Response:
    {
        "test_texts": [
            {"text": "今天天气真好！", "expected": "positive"},
            {"text": "我很生气！", "expected": "negative"},
            {"text": "好的，我知道了。", "expected": "neutral"}
        ],
        "results": [...]
    }
    """
    try:
        test_texts = [
            {"text": "今天天气真好！", "expected": "positive"},
            {"text": "我很生气！", "expected": "negative"},
            {"text": "好的，我知道了。", "expected": "neutral"},
            {"text": "哈哈，太搞笑了！😂", "expected": "positive"},
            {"text": "😭我很难过", "expected": "negative"}
        ]
        
        results = []
        for test_case in test_texts:
            text = test_case["text"]
            expected = test_case["expected"]
            
            result = emotion_analyzer.analyze_emotion_combined(text)
            result["expected"] = expected
            result["correct"] = result["emotion"] == expected
            
            results.append(result)
        
        return jsonify({
            "test_texts": test_texts,
            "results": results,
            "accuracy": sum(1 for r in results if r["correct"]) / len(results)
        })
        
    except Exception as e:
        logger.error(f"Error testing emotion analysis: {e}")
        return jsonify({
            "error": str(e)
        }), 500

if __name__ == '__main__':
    logger.info("Starting Emotion Analysis Service...")
    app.run(host='0.0.0.0', port=5001, debug=True)
